package log

import (
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"time"
	"fmt"
)

var SugarLogger *zap.SugaredLogger

type Config struct {
	Filename string `json:"filename" mapstructure:"filename"`
	MaxSize int `json:"maxsize" mapstructure:"maxsize"`
	MaxBackups int `json:"maxbackups" mapstructure:"maxbackups"`
	MaxAge int `json:"maxage" mapstructure:"maxage"`
	Compress bool `json:"compress" mapstructure:"compress"`

}



func (s *Config) InitLogger() {

	encoder := s.getEncoder()
	writeSyncer := s.getLogWriter()
	core := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)

	// zap.AddCaller()  添加将调用函数信息记录到日志中的功能。
	logger := zap.New(core, zap.AddCaller())
	SugarLogger = logger.Sugar()
	// sugarLogger.Info("this is info message")
	// sugarLogger.Infof("this is %s, %d", "aaa", 1234)
	// sugarLogger.Error("this is error message")
	// sugarLogger.Info("this is info message")
}

func (s *Config) getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder // 修改时间编码器

	// 在日志文件中使用大写字母记录日志级别
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	// NewConsoleEncoder 打印更符合人们观察的方式
	return zapcore.NewConsoleEncoder(encoderConfig)
}

func (s *Config) getLogWriter() zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   fmt.Sprintf("%v%v.log", s.Filename, time.Now().Format("2006-01-02")),
		MaxSize:    s.MaxSize,
		MaxBackups: s.MaxBackups,
		MaxAge:     s.MaxAge,
		Compress:   s.Compress,
	}
	return zapcore.AddSync(lumberJackLogger)
}




